package com.chen.controller;

import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chen.entity.Order;
import com.chen.entity.UserRechargeOrders;
import com.chen.mapper.OrderMapper;
import com.chen.service.TokenService;
import com.chen.service.UserRechargeOrdersService;
import com.chen.service.UserService;
import com.chen.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cws
 * @since
 */
@RestController
@Slf4j
public class PayCallBackController {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @Resource
    private UserRechargeOrdersService userRechargeOrdersService;

    @Resource
    private OrderMapper orderMapper;

    /**
     * 支付宝支付回调  不建议改写法
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/pay/notify")
    public Result payNotify(HttpServletRequest request) throws Exception {
        log.info("---------------进入支付回调---------------");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
//            // 支付宝验签
        if (Factory.Payment.Common().verifyNotify(params)) {
            String subject = params.get("subject");
            log.info("订单信息：{}", subject);
            HashMap<String, String> paramsMap = JSONUtil.toBean(subject, HashMap.class);
            String type = paramsMap.get("type");
            if (type.equals("user")) {
                log.info("*****************************用户充值回调**************************");
                UserRechargeOrders userRechargeOrders = userRechargeOrdersService.getOne(new LambdaUpdateWrapper<UserRechargeOrders>()
                        .eq(UserRechargeOrders::getOrderNumber, paramsMap.get("orderSn")));
                userRechargeOrders.setStatus("成功");
                userRechargeOrders.setPaidAt(LocalDateTime.now());
                boolean update = userRechargeOrdersService.updateById(userRechargeOrders);
                log.info("充值订单状态更新：{}", update);
                String totalAmount = params.get("total_amount");
                BigDecimal bigDecimal = new BigDecimal(totalAmount);
                boolean res = userService.updateAmout(userRechargeOrders.getUserId(), bigDecimal);
                log.info("用户余额更新：{}", res);
//                刷新缓存
                tokenService.refreshToken(paramsMap.get("token"));
            }else{
                log.info("*****************************订单充值回调**************************");
                Order orderSn = orderMapper.selectOne(new LambdaQueryWrapper<Order>()
                        .eq(Order::getOrderSn, paramsMap.get("orderSn")));
                //更新订单状态
                int i = orderMapper.updateStatus(orderSn.getId(),1);
                log.info("订单状态修改：{}", i);
                Long userId = orderSn.getUserId();
                Integer integration = orderSn.getIntegration();
                boolean res =  userService.updateIntegration(userId, integration);
                log.info("用户积分更新：{}", res);
                //                刷新缓存
                tokenService.refreshToken(paramsMap.get("token"));
            }
            // 验签通过
            log.info("交易状态: {}", params.get("trade_status"));
            log.info("支付宝交易凭证号: {}", params.get("trade_no"));
            log.info("商户订单号: {}", params.get("out_trade_no"));
            log.info("交易金额: {}", params.get("total_amount"));
            log.info("买家在支付宝唯一id: {}", params.get("buyer_id"));
            log.info("买家付款时间: {}", params.get("gmt_payment"));
            log.info("买家付款金额: {}", params.get("buyer_pay_amount"));
            // 更新订单状态
            return Result.success();
        }
        return Result.success();
    }
}

